package com.wframe.project.jnd.util;

import com.frame.database.JdataBean;
import org.apache.commons.lang.StringUtils;

import javax.persistence.Column;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.*;

/**
 * Created by lwb on 2017/6/3.
 */
public class TransformUtils {

    public static <T> T trans(JdataBean bean, Class<T> clazz) throws Exception {
        T instance = clazz.newInstance();

        List<Field> fieldList = new ArrayList<>();
        Class<? super T> tmpClass = clazz;
        while (tmpClass != null && !tmpClass.getName().toLowerCase().equals("java.lang.object")) {
            fieldList.addAll(Arrays.asList(tmpClass.getDeclaredFields()));
            tmpClass = tmpClass.getSuperclass();
        }

        for (Field field : fieldList) {
            String columnName = field.getName();
            Column column = field.getAnnotation(Column.class);
            if (Objects.nonNull(column)) {
                columnName = column.name();
            }
            setValue(field, instance, bean.get(columnName));
        }
        return instance;
    }

    private static <T> void setValue(Field field, T instance, Object obj) throws IllegalAccessException {
        if (Objects.nonNull(obj)) {
            field.setAccessible(true);
            field.set(instance, obj);
        }
    }

    public static String trans(String parm) {
        if (StringUtils.isNotBlank(parm)) {
            parm = parm.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
        }
        return parm;
    }

    public static String getValue(String str) {
        if (StringUtils.isBlank(str)) {
            str = null;
        }
        return str;
    }
}
